package com.hubiao.spring.demo.action;

import com.hubiao.spring.demo.service.IModifyService;
import com.hubiao.spring.demo.service.IQueryService;
import com.hubiao.spring.framework.annotation.HbAutowired;
import com.hubiao.spring.framework.annotation.HbController;
import com.hubiao.spring.framework.annotation.HbRequestMapping;
import com.hubiao.spring.framework.annotation.HbRequestParam;
import com.hubiao.spring.framework.webmvc.GPModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 公布接口url
 *
 * @author Tom
 */
@HbController
@HbRequestMapping("/web")
public class MyAction {

    @HbAutowired
    IQueryService queryService;
    @HbAutowired
    IModifyService modifyService;

    @HbRequestMapping("/query.json")
    public GPModelAndView query(HttpServletRequest request, HttpServletResponse response,
                                @HbRequestParam("name") String name) {
        String result = queryService.query( name );
        System.out.println( result );
        return out( response, result );
    }

    @HbRequestMapping("/add*.json")
    public GPModelAndView add(HttpServletRequest request, HttpServletResponse response,
                              @HbRequestParam("name") String name, @HbRequestParam("addr") String addr) {
        String result = modifyService.add( name, addr );
        return out( response, result );
    }

    @HbRequestMapping("/remove.json")
    public GPModelAndView remove(HttpServletRequest request, HttpServletResponse response,
                                 @HbRequestParam("id") Integer id) {
        String result = modifyService.remove( id );
        return out( response, result );
    }

    @HbRequestMapping("/edit.json")
    public GPModelAndView edit(HttpServletRequest request, HttpServletResponse response,
                               @HbRequestParam("id") Integer id,
                               @HbRequestParam("name") String name) {
        String result = modifyService.edit( id, name );
        return out( response, result );
    }


    private GPModelAndView out(HttpServletResponse resp, String str) {
        try {
            resp.getWriter().write( str );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
